//
//  DataManagerViewController.m
//  DataManager
//
//  Created by Michael Hinds on 2/8/09.
//  Copyright University of Arkansas 2009. All rights reserved.
//

#import "OldDataManager.h"

@implementation OldDataManager
@synthesize txtArea, receivedData;

- (IBAction) updateText:(id) sender {
	
	//print stuff
	txtArea.text = [txtArea.text stringByAppendingFormat:@"Hello \n\n"];
	NSLog(@"\n\n");
	NSLog(@"Quote Button was clicked!!!");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"Profile Button was clicked!"];
	
	// Create the URL
	NSURL *myURL = [[NSURL alloc] initWithString:@"http://www.kaching.com/api/users/8/portfolio"];
	
	//print stuff
	NSLog(@"Absolute String: %@", [myURL absoluteString]);
	NSLog(@"Fragment: %@", [myURL fragment]);
	NSLog(@"Host: %@", [myURL host]);
	NSLog(@"Parameter String: %@", [myURL parameterString]);
	NSLog(@"Password: %@", [myURL password]);
	NSLog(@"Path: %@", [myURL path]);
	NSLog(@"Port: %d", [myURL port]);
	NSLog(@"Query: %@", [myURL query]);
	NSLog(@"Relative Path: %@", [myURL relativePath]);
	NSLog(@"Relative String: %@", [myURL relativeString]);
	NSLog(@"Resource Specifier: %@", [myURL resourceSpecifier]);
	NSLog(@"Scheme: %@", [myURL scheme]);
	NSLog(@"User: %@", [myURL user]);
	NSLog(@"***************************************************************");
	
	// Create the URL Request
	NSMutableURLRequest *myURLRequest = [NSMutableURLRequest requestWithURL:myURL];
	//specify key 
	[myURLRequest setHTTPMethod:@"GET"];
	NSLog(@"\n\n");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"\n\n"];
	NSLog(@"Request created!!!");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"Request created!!"];
	NSLog(@"URL: %@", [[myURLRequest URL] absoluteString]);
	txtArea.text = [txtArea.text stringByAppendingFormat:@"URL: %@", [[myURLRequest URL] absoluteString]];
	NSLog(@"HTTP Method: %@", [myURLRequest HTTPMethod]);
	txtArea.text = [txtArea.text stringByAppendingFormat:@"HTTP Method: %@", [myURLRequest HTTPMethod]];
	NSLog(@"HTTP Body: %@", [[myURLRequest HTTPBody] description]);
	txtArea.text = [txtArea.text stringByAppendingFormat:@"HTTP Body: %@", [[myURLRequest HTTPBody] description]];
	NSLog(@"***************************************************************");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"\n***************************************"];
	/* 
	 Create the connection with the URLRequest that was just created.
	 Note: The NSURLConnection class implements four delegate methods:
	 1. connection: didReceiveResponse:
	 2. connection: didReceiveData:
	 3. connection: didFailWithError:
	 4. connectonDidFinishLoading:
	 
	 This means that, when an instance of NSURLConnection is created, those four methods have to be created
	 somewhere in the delegate class.  Since the delegate is set to self, that means this class needs to implement
	 those four methods.	 
	 */
	NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate:self];
	
	// If the connection was successful...
	if (myConnection != nil)
	{
		NSLog(@"Connection was: SUCCESSFUL");
		txtArea.text = [txtArea.text stringByAppendingFormat:@"Connection was: SUCCESSFUL"];
		
		// Create an NSMutableData that will hold the received data.
		// Note: receivedData is declared as a method instance in _____
		receivedData = [[NSMutableData data] retain];
	}
	// The connection was unsuccessful...
	else
	{
		NSLog(@"Connection was: UNSUCCESSFUL");
		txtArea.text = [txtArea.text stringByAppendingFormat:@"Connection was: UNSUCCESSFUL"];
	}
}

// This method is called when the server has determined that it has enough information to create the NSURLResponse.	
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSLog(@"The 'didReceiveResponse' method was called...");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"The 'didReceiveResponse' method was called..."];
	
	// It can be called multiple times (e.g., in the case of a redirect), so each time re reset the data.
	// receivedData is declared as a method instance elsewhere
	[receivedData setLength:0];
}

// This method is called as the data is received.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	NSLog(@"The 'didReceiveData' method was called...");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"The 'didReceiveData' method was called..."];
	
	// append the new data to the receivedData
	// receivedData is declared as a method instance elsewhere
	[receivedData appendData:data];
}

// This method is called if an error was encountered during the download.
- (void)connection:(NSConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"The 'didFailWithError' method was called...");
	txtArea.text = [txtArea.text stringByAppendingFormat:@"The 'didFailWithError' method was called..."];
	
	// release the connection and the data object
	[connection release];
	[receivedData release];
}

// This method is called when the connection has successfully downloaded the request
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// Create new SBJSON parser object 
	SBJSON *parser = [[SBJSON alloc] init]; 
	
	
	NSLog(@"Succeeded! Received %d bytes of data!", [receivedData length]);
	txtArea.text = [txtArea.text stringByAppendingFormat:@"Succeeded! Received %d bytes of data!", [receivedData length]];
	
	NSLog(@"%@", receivedData);
	//txtArea.text = [txtArea.text stringByAppendingFormat:@"%@", receivedData];
	//		NSLog(@"%@", [receivedData description]);
	
	NSString *theJSON = [[NSString alloc] initWithBytes: [receivedData mutableBytes] length: [receivedData length] encoding: NSUTF8StringEncoding];
	NSLog(theJSON);
	txtArea.text = [txtArea.text stringByAppendingFormat:@"%@", theJSON];
	
	
	//parse the JSON
	NSDictionary *parsedJSONdict = [parser objectWithString:theJSON error:NULL];
	txtArea.text = [txtArea.text stringByAppendingFormat:@"\n\n Number of elements in NSDictionary: \n%d", [parsedJSONdict count]];
	
	NSArray *parsedJSONarray = [parser objectWithString:theJSON error:NULL];
	txtArea.text = [txtArea.text stringByAppendingFormat:@"\n\n Number of elements in NSArray: \n%d", [parsedJSONarray count]];
	
	// release the connection and data object
	[connection release];
	[receivedData release];
	[theJSON release];
	[parsedJSONdict release];
	[parsedJSONarray release];
}

//resigns the first responder, so that the keyboard is not available for editing the text View
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{	
	return NO;
}
/*
 // Override initWithNibName:bundle: to load the view using a nib file then perform additional customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically.
 - (void)loadView {
 }
 */


/*
 // Implement viewDidLoad to do additional setup after loading the view.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[txtArea release];
    [super dealloc];
}

@end
